<template>
  <div class="room-list-container">
    <!-- 主标题区域 -->
    <div class="main-header">
      <h1 class="main-title">社交中心</h1>
      <p class="main-subtitle">管理好友关系，加入游戏房间</p>
    </div>

    <!-- 现代化的Tab切换栏 -->
    <div class="modern-tab-container">
      <div class="tab-header">
        <button 
          v-for="tab in tabs" 
          :key="tab.id"
          :class="['tab-button', { 'active': currentTab === tab.id }]"
          @click="switchTab(tab.id)"
        >
          <span class="tab-icon">{{ tab.icon }}</span>
          <span class="tab-label">{{ tab.label }}</span>
          <span v-if="tab.badge" class="tab-badge">{{ tab.badge }}</span>
        </button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 好友管理 Tab -->
      <div v-if="currentTab === 'friends'" class="tab-content friends-content">
        <div class="friends-header">
          <h2 class="section-title">好友管理</h2>
          <div class="header-actions">
            <button @click="goToFriendRequests" class="action-btn requests-btn">
              <span class="btn-icon">📨</span>
              好友申请
              <span v-if="friendRequestCount > 0" class="badge">{{ friendRequestCount }}</span>
            </button>
            <button @click="showAddFriendDialog = true" class="action-btn add-btn">
              <span class="btn-icon">➕</span>
              添加好友
            </button>
          </div>
        </div>

        <!-- 好友列表 -->
        <div v-if="friends.length > 0" class="friends-grid">
          <div v-for="friend in friends" :key="friend.id" class="friend-card">
            <div class="friend-avatar">
              <span class="avatar-text">{{ friend.friend_user_avatar || friend.friend_user_name?.charAt(0) || '默' }}</span>
              <div class="online-indicator" :class="{ 'online': friend.isOnline }"></div>
            </div>
            <div class="friend-info">
              <div class="friend-name">{{ friend.friend_user_name || '未知用户' }}</div>
              <div class="friend-status" :class="{ 'online': friend.isOnline }">
                {{ friend.isOnline ? '🟢 在线' : '⚪ 离线' }}
              </div>
            </div>
            <div class="friend-actions">
              <button @click="startChat(friend.friend_user_id)" class="chat-btn" title="开始聊天">
                <span class="btn-icon">💬</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <div class="empty-icon">👥</div>
          <h3 class="empty-title">暂无好友</h3>
          <p class="empty-description">添加好友开始社交吧！</p>
          <button @click="showAddFriendDialog = true" class="primary-btn">
            <span class="btn-icon">➕</span>
            添加好友
          </button>
        </div>
      </div>

      <!-- 房间列表 Tab -->
      <div v-if="currentTab === 'rooms'" class="tab-content rooms-content">
        <div class="rooms-header">
          <h2 class="section-title">房间列表</h2>
          <div class="header-actions">
            <div class="refresh-control">
              <span class="refresh-label">自动刷新</span>
              <switch :checked="autoRefresh" @change="toggleAutoRefresh" />
            </div>
            <button @click="showCreateRoomDialog = true" class="action-btn create-btn">
              <span class="btn-icon">🏠</span>
              创建房间
            </button>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <p class="loading-text">加载中...</p>
        </div>

        <!-- 房间列表 -->
        <div v-else-if="rooms && rooms.length > 0" class="rooms-grid">
          <div v-for="room in rooms" :key="getRoomId(room)" 
               :class="['room-card', { 'new-room': getRoomId(room) === newRoomId }]">
            <div class="room-header">
              <div class="room-name">{{ room.name }}</div>
              <div class="room-type-badge">{{ getRoomTypeText(room.tag || room.type) }}</div>
            </div>
            <div class="room-meta">
              <div class="room-stats">
                <span class="stat-item">
                  <span class="stat-icon">👥</span>
                  {{ room.user_count || 0 }}/{{ room.max_users || 2 }} 人
                </span>
                <span class="stat-item">
                  <span class="stat-icon">{{ room.is_playing ? '🎮' : '⏳' }}</span>
                  {{ room.is_playing ? '游戏中' : '等待中' }}
                </span>
              </div>
            </div>
            <div class="room-actions">
              <button @click="joinRoom(getRoomId(room))" class="join-btn">
                <span class="btn-icon">🚪</span>
                加入
              </button>
              <button 
                v-if="isRoomCreator(room)" 
                @click="deleteRoom(room)" 
                class="delete-btn"
                title="删除房间"
              >
                <span class="btn-icon">🗑️</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <div class="empty-icon">🏠</div>
          <h3 class="empty-title">暂无可用房间</h3>
          <p class="empty-description">创建一个新房间开始游戏吧！</p>
          <button @click="showCreateRoomDialog = true" class="primary-btn">
            <span class="btn-icon">🏠</span>
            创建房间
          </button>
        </div>
      </div>
    </div>

    <!-- 添加好友弹窗 -->
    <div v-if="showAddFriendDialog" class="modal-overlay" @click="showAddFriendDialog = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">添加好友</h3>
          <button @click="showAddFriendDialog = false" class="close-btn">✕</button>
        </div>
        
        <div class="search-section">
          <div class="search-input-wrapper">
            <span class="search-icon">🔍</span>
            <input
              v-model="searchUsername"
              placeholder="输入用户名搜索"
              class="search-input"
              @keyup.enter="searchUser"
            >
          </div>
          <button @click="searchUser" class="search-btn">
            <span class="btn-icon">🔍</span>
            搜索
          </button>
        </div>

        <div v-if="searchResult" class="search-result">
          <div class="user-info">
            <div class="user-avatar">
              <span class="avatar-text">{{ searchResult.avatar || '默' }}</span>
            </div>
            <div class="user-details">
              <div class="user-name">{{ searchResult.username }}</div>
              <div class="user-id">ID: {{ searchResult.id }}</div>
            </div>
          </div>
          <button @click="sendFriendRequest(searchResult.id)" class="add-friend-btn">
            <span class="btn-icon">➕</span>
            添加好友
          </button>
        </div>

        <div v-else-if="searchUsername && !searchResult" class="no-result">
          <div class="no-result-icon">🔍</div>
          <div class="no-result-text">未找到相关用户</div>
        </div>
      </div>
    </div>

    <!-- 创建房间弹窗 -->
    <div v-if="showCreateRoomDialog" class="modal-overlay" @click="showCreateRoomDialog = false">
      <div class="modal-content create-room-modal" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">创建房间</h3>
          <button @click="showCreateRoomDialog = false" class="close-btn">✕</button>
        </div>
        
        <div class="form-content">
          <div class="form-group">
            <label class="form-label">房间名称</label>
            <input
              v-model="roomName"
              placeholder="输入房间名称"
              class="form-input"
              :class="{ 'error': roomNameError }"
            >
            <div v-if="roomNameError" class="error-message">{{ roomNameError }}</div>
          </div>
          
          <div class="form-group">
            <label class="form-label">房间类型</label>
            <select v-model="roomType" class="form-select">
              <option value="chat">聊天室</option>
              <option value="snake">蛇蛇大作战</option>
              <option value="tictactoe">井字棋</option>
              <option value="gomoku">五子棋</option>
            </select>
          </div>
          
          <div class="form-group">
            <label class="form-label">最大人数</label>
            <select v-model="maxUsers" class="form-select">
              <option value="2">2人</option>
              <option value="4">4人</option>
              <option value="8">8人</option>
            </select>
          </div>
          
          <div class="form-group">
            <label class="form-label">房间密码（可选）</label>
            <input
              v-model="roomPassword"
              placeholder="输入房间密码"
              type="password"
              class="form-input"
            >
          </div>
          
          <div class="form-group">
            <label class="form-label">房间描述（可选）</label>
            <textarea
              v-model="roomDescription"
              placeholder="房间描述"
              class="form-textarea"
            ></textarea>
          </div>
          
          <div class="form-actions">
            <button @click="createRoom" class="primary-btn">
              <span class="btn-icon">✅</span>
              创建房间
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-toast">
      {{ errorMessage }}
      <button @click="errorMessage = ''" class="close-error-btn">×</button>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue';
import { onMounted, onUnmounted, onActivated } from 'vue'
import { roomApi } from '@/api'
import { friendsApi } from '@/api'
import { useUserStore } from '@/stores/user'
import { handleApiError } from '@/utils/error-handler'
import { checkLoginStatus, getCurrentUserId, getCurrentUserInfo } from '@/utils/auth'
import { createRoomListManager } from '@/utils/websocket-manager'

uni.showToast({ title: '进入社交中心', icon: 'none', duration: 1000 })

// 获取用户信息
const userInfo = getCurrentUserInfo()
const userId = userInfo?.userId || 'user123'
const userName = userInfo?.userName || '玩家1'

// 状态管理
const userStore = useUserStore()

// Tab配置
const tabs = computed(() => [
  { 
    id: 'friends', 
    label: '好友', 
    icon: '👥',
    badge: friendRequestCount.value > 0 ? friendRequestCount.value : null
  },
  { 
    id: 'rooms', 
    label: '房间', 
    icon: '🏠'
  }
])

const currentTab = ref('rooms')

// 房间数据
const rooms = ref([])
const showCreateRoomDialog = ref(false)
const roomName = ref('')
const roomType = ref('chat')
const roomPassword = ref('')
const roomDescription = ref('')
const maxUsers = ref('2')
const roomTimeout = ref('')

// 新房间ID，用于高亮显示
const newRoomId = ref(null)

// 错误状态
const roomNameError = ref('')
const errorMessage = ref('')

// 加载状态
const loading = ref(false)

// 刷新控制
const autoRefresh = ref(uni.getStorageSync('roomListAutoRefresh') !== false)
const refreshInterval = ref(30000)

// 好友功能相关状态
const friends = ref([])
const friendRequestCount = ref(0)
const showAddFriendDialog = ref(false)
const searchUsername = ref('')
const searchResult = ref(null)

// Tab切换函数
const switchTab = (tabId) => {
  currentTab.value = tabId
  if (tabId === 'rooms') {
    getRoomList()
  } else {
    getFriendList()
    getFriendRequestCount()
  }
}

// 获取房间类型文本
const getRoomTypeText = (type) => {
  const typeMap = {
    'chat': '聊天',
    'snake': '蛇蛇大作战',
    'tictactoe': '井字棋',
    'gomoku': '五子棋',
    'ruins': '遗迹探索',
    'game': '农场经营',
    'farm': '农场经营'
  }
  return typeMap[type] || type || '未指定'
}

// 获取房间ID的辅助函数
const getRoomId = (room) => {
  const id = room.id || room.room_id || room._id;
  return String(id);
}

// 好友功能相关函数
const getFriendList = async () => {
  try {
    const res = await friendsApi.getFriendList()
    console.log('获取好友列表响应:', res)
    friends.value = res.data || []
  } catch (error) {
    console.error('获取好友列表失败:', error)
  }
}

const getFriendRequestCount = async () => {
  try {
    const res = await friendsApi.getFriendRequests()
    friendRequestCount.value = res.data?.length || 0
  } catch (error) {
    console.error('获取好友申请数量失败:', error)
  }
}

const searchUser = async () => {
  if (!searchUsername.value.trim()) {
    uni.showToast({ title: '请输入用户名', icon: 'none' })
    return
  }

  try {
    const res = await friendsApi.searchUser(searchUsername.value)
    console.log('搜索用户响应:', res)
    if (res.data && res.data.length > 0) {
      searchResult.value = res.data[0]
    } else {
      searchResult.value = null
      uni.showToast({ title: '未找到相关用户', icon: 'none' })
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    uni.showToast({ title: '搜索用户失败', icon: 'none' })
  }
}

const sendFriendRequest = async (userId) => {
  try {
    const currentUserId = getCurrentUserId(true)
    if (!currentUserId) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }

    await friendsApi.sendFriendRequest({
      from_user_id: currentUserId,
      to_user_id: userId,
      message: '我想和你成为好友'
    })
    
    uni.showToast({ title: '好友申请已发送', icon: 'success' })
    showAddFriendDialog.value = false
    searchUsername.value = ''
    searchResult.value = null
  } catch (error) {
    console.error('发送好友申请失败:', error)
    uni.showToast({ title: '发送好友申请失败', icon: 'none' })
  }
}

const startChat = async (friendUserId) => {
  try {
    const res = await friendsApi.getOrCreateChatRoom(friendUserId)
    uni.setStorageSync('roomId', res.data.roomId)
    uni.navigateTo({ url: '/pages/chat/chat' })
  } catch (error) {
    console.error('创建聊天房间失败:', error)
    uni.showToast({ title: '进入聊天失败', icon: 'none' })
  }
}

const goToFriendRequests = () => {
  uni.navigateTo({ url: '/pages/friends/requests' })
}

// 房间功能相关函数
const toggleAutoRefresh = (e) => {
  autoRefresh.value = e.detail.value
  uni.setStorageSync('roomListAutoRefresh', autoRefresh.value)
  refreshInterval.value = autoRefresh.value ? 30000 : 300000
  
  if (intervalId) {
    clearInterval(intervalId)
  }
  if (autoRefresh.value) {
    intervalId = setInterval(() => {
      getRoomList()
    }, refreshInterval.value)
  }
  
  console.log('自动刷新设置已更新:', {
    autoRefresh: autoRefresh.value,
    refreshInterval: refreshInterval.value
  })
}

const getRoomList = async () => {
  if (loading.value) return
  
  loading.value = true
  try {
    const res = await roomApi.getRooms()
    console.log('获取房间列表响应:', res)
    
    if (res && res.data && Array.isArray(res.data)) {
      rooms.value = res.data.map(room => ({
        ...room,
        user_count: room.user_count || 0
      }))
    } else if (Array.isArray(res)) {
      rooms.value = res.map(room => ({
        ...room,
        user_count: room.user_count || 0
      }))
    } else {
      rooms.value = []
    }
    
  } catch (error) {
    console.error('获取房间列表失败:', error)
    errorMessage.value = '获取房间列表失败'
    rooms.value = []
  } finally {
    loading.value = false
  }
}

const validateForm = () => {
  roomNameError.value = ''
  
  if (!roomName.value.trim()) {
    roomNameError.value = '请输入房间名称'
    return false
  }
  
  if (roomName.value.trim().length < 2) {
    roomNameError.value = '房间名称至少2个字符'
    return false
  }
  
  if (roomName.value.trim().length > 20) {
    roomNameError.value = '房间名称不能超过20个字符'
    return false
  }
  
  return true
}

const createRoom = async () => {
  if (!validateForm()) {
    return
  }

  try {
    const res = await roomApi.createRoom(
      roomName.value,
      roomType.value,
      roomPassword.value,
      roomDescription.value,
      parseInt(maxUsers.value),
      roomTimeout.value ? parseInt(roomTimeout.value) : undefined,
      { userId, userName }
    )
    uni.showToast({ title: '房间创建成功', icon: 'success' })
    showCreateRoomDialog.value = false
    
    newRoomId.value = res.room_id || res.id || res.data?.room_id || res.data?.id
    
    roomName.value = ''
    roomType.value = 'chat'
    roomPassword.value = ''
    roomDescription.value = ''
    maxUsers.value = '2'
    roomTimeout.value = ''
    
    await getRoomList()
    
    setTimeout(() => {
      newRoomId.value = null
    }, 3000)
  } catch (error) {
    handleApiError(error, '创建房间')
    errorMessage.value = '创建房间失败'
  }
}

const joinRoom = async (roomId) => {
  if (!roomId) {
    uni.showToast({ title: '房间ID无效', icon: 'none' })
    return
  }
  
  try {
    await roomApi.joinRoom(roomId)
    uni.setStorageSync('roomId', String(roomId))
    
    const room = rooms.value.find(r => getRoomId(r) === roomId)
    
    if (!room) {
      uni.showToast({ title: '房间信息不存在', icon: 'none' })
      return
    }
    
    const gameType = room.tag || room.type || 'chat'
    let targetPath = '/pages/chat/chat'
    
    if (gameType === 'snake') {
      targetPath = '/pages/games/snake/snake'
    } else if (gameType === 'gomoku') {
      targetPath = '/pages/games/gomoku/gomoku'
    } else if (gameType === 'tictactoe') {
      targetPath = '/pages/games/tictactoe/tictactoe'
    } else if (gameType === 'ruins') {
      targetPath = '/pages/games/ruins/ruins'
    } else if (gameType === 'game' || gameType === 'farm') {
      targetPath = '/pages/games/game/game'
    }
    
    uni.navigateTo({ url: targetPath })
  } catch (error) {
    handleApiError(error, '加入房间')
    errorMessage.value = '加入房间失败'
  }
}

const deleteRoom = async (room) => {
  const roomId = getRoomId(room)

  if (!roomId) {
    uni.showToast({ title: '房间ID无效', icon: 'none' })
    return
  }

  uni.showModal({
    title: '确认删除',
    content: `确定要删除房间 "${room.name}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await roomApi.deleteRoom(roomId, userId)
          uni.showToast({ title: '删除成功', icon: 'success' })
          await getRoomList()
        } catch (error) {
          handleApiError(error, '删除房间')
          errorMessage.value = '删除房间失败'
        }
      }
    }
  })
}

const isRoomCreator = (room) => {
  return room.creator_id == userId
}

// 存储定时器ID
let intervalId = null

// WebSocket管理器
let wsManager = null;

const initWebSocket = () => {
  try {
    wsManager = createRoomListManager(userId, userName, {
      onOpen: () => {
        console.log('房间列表WebSocket连接成功')
      },
      onMessage: (message) => {
        console.log('房间列表收到消息:', message);
      },
      onError: (error) => {
        console.error('房间列表WebSocket连接错误:', error);
      }
    })
    
    wsManager.connect()
  } catch (error) {
    console.error('创建房间列表WebSocket管理器失败:', error)
  }
}

const closeWebSocket = () => {
  if (wsManager) {
    wsManager.close();
    wsManager = null;
  }
};

// 组件挂载时
onMounted(() => {
  if (!checkLoginStatus()) {
    uni.navigateTo({ url: '/pages/login/login' })
    return
  }

  const savedAutoRefresh = uni.getStorageSync('roomListAutoRefresh')
  if (savedAutoRefresh !== null && savedAutoRefresh !== undefined) {
    autoRefresh.value = savedAutoRefresh
    refreshInterval.value = autoRefresh.value ? 30000 : 300000
  }

  getRoomList()
  getFriendList()
  getFriendRequestCount()
  initWebSocket();
  
  if (autoRefresh.value) {
    intervalId = setInterval(() => {
      getRoomList()
    }, refreshInterval.value)
  }
})

onActivated(() => {
  if (userStore.isLogin) {
    getRoomList()
    getFriendList()
    getFriendRequestCount()
  }
});

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = null
  }
  closeWebSocket();
})
</script>

<style src="./room-list.css"></style>